<?php
namespace app\api\controller;
use app\common\controller\BaseApi;

/* 智游人 api*/
class ZYRApi extends  BaseApi
{
	//测试url http://test.smartfuns.com:3507
	//正式url http://clubacylm.smartfuns.com/
	//进出门禁
	const GetContractInfo="http://clubacylm.smartfuns.com/v1/member/syncMemberInfo";// 获取会员信息
	const CheckIn="http://clubacylm.smartfuns.com/v1/access/in";//进场
	const ConfirmCheckOut="http://clubacylm.smartfuns.com/v1/access/out"; //出场
	
	protected $BranchID;//品牌id
	protected $Key;//Aec key
	
	protected $shop_id;//店铺id
	
	/**
	 * 测试地址
	 * */
	 public function _initialize()
    {
    }
	
	private function zyr_error($code){
		$error=array('0'=>"失败(zyr)",'1'=>"成功","2"=>"参数不全(zyr)","3"=>"无效的BranchID(zyr)","4"=>"无效的CardNo(zyr)","5"=>"卡没绑定会员(zyr)");
		if(!isset($error[$code])){
			return "未知错误(zyr)！";
		}else{
			return $error[$code];
		}
	}
	function test(){
		$result=openssl_decrypt(base64_decode('txQuKgE7gTx/yk3pZ2IJ3w=='), "aes-256-cbc", $this->Key, true, str_repeat(chr(0), 16));
		var_dump($result);
	}
	/**
	 * 解密
	 */
	private function decrypt($data){
		$result=openssl_decrypt(base64_decode($data), "aes-256-cbc", $this->Key, true, str_repeat(chr(0), 16));
		if(empty($result)){
			$this->ajax_error('','',"请配置智游人代码(解密错误)");
		}else{
			return json_decode($result,TRUE);
		}
	} 
		
	/////////////////////////////////////////获取智游人数据////////////////////////////////////////////////////////////////
	/**
	 * 方法前操作获取店铺信息
	 */
	function before_method($shop_id){
		if(empty($shop_id)){
			$this->ajax_error('','',"店铺id 为空");
		}else{
			$this->shop_id=$shop_id;
		}
		$config=cache("ExtraConfig_".$this->shop_id);
    	if(empty($config)){
			 $config=db("Shop")->where("id=".$this->shop_id)->value("extra_config");
			 if(empty($config)){
			 	$this->ajax_error('','',"请配置智游人代码");
			}
			 $config=json_decode($config,TRUE);
			 cache("ExtraConfig_".$this->shop_id,$config);
    	} 
    	$this->BranchID=$config['BranchID'];
		$this->Key=$config['Key'];
	}
	/**
	 * 获取合同号
	 * @param $card_no
	 * @return $data
	 * [
	 *	    {
	 *		        "ContractID": "06162ef0-7022-433e-80bd-7d9d44dc113c",
	 *		        "MemberID": "5c5313c8-aa5b-493a-8664-88e89b19a6ca",
	 *		        "MemberName": "ERCC",
	 *		        "Sex": "鐢�",
	 *		        "Mobile": "18523020102",
	 *		        "CardNo": "2238082314",
	 *		        "StartDate": "2017-10-19",
	 *		        "EndDate": "2018-10-28",
	 *		        "ContractStatus": 1,
	 *		        "MembershipType": 2,
	 *		        "MembershipTypeName": "骞存湀鍗�",
	 *		        "SurplusNum": "0",
	 *		        "StoredSumValue": "0.00"
	 *		    }
	 *		]
	 * http://smartgym.com/api/ZYRApi/GetContractInfo/card_no/0723322990/shop_id/54
	 */
	function GetContractInfo($card_no,$shop_id){
		$this->before_method($shop_id);
		$result=http_get(self::GetContractInfo,['BranchID'=>$this->BranchID,"CardNo"=>$card_no]);
		if($result['flag']){
			$json= $this->decrypt($result['data']);
			if($json['Result']==1){
				return template_success("成功(zry)",
							array(
								  "ContractID"=>$json['MemberID'],
								  "MemberID"=>$json['MemberID'],
								  "StartDate"=>$json['StartDate'],
								  "MemberName"=>$json['MemberName'],
								  "EndDate"=>$json['EndDate'],
								  "ContractStatus"=>$json['ContractStatus'],
								  "Sex"=>"",
								  "Mobile"=>$json['Mobile'],
								  "CardNo"=>$card_no,
								  "MembershipType"=>$json['MembershipType'],
								  "MembershipTypeName"=>$json['MembershipTypeName'],
								  "SurplusNum"=>$json['SurplusNum'],
								  "StoredSumValue"=>0,
								  "MemberUrl"=>$json['MemberUrl'],
								  //"MemberUrl"=>"http://cdn.smartfuns.com/upload/club/clubmember/images/2018/04/24/21520180424153659.jpg"
					));
			}else{
				return template_error($this->zyr_error($json['Result'])); 
			}			
		}else{
			return template_error($result['msg']);
		}
	}
	/**
	 * 入场操作
	 * http://smartgym.com/api/ZYRApi/CheckIn/interface/
	 */
	function CheckIn($interface){
		$shop_id=$interface['shop_id'];
		$card_no=$interface['card_no'];
		$member_id=$interface['member_id'];
		$this->before_method($shop_id);
		$result=http_get(self::CheckIn,['CardNo'=>$card_no,'BranchID'=>$this->BranchID,"DoorID"=>$shop_id,"MemberID"=>$member_id]);
		if($result['flag']){
			$json= $this->decrypt($result['data']);
			if($json['Result']==1){
				return template_success("成功(zyr)",$json);
			}else{
				return template_error($this->zyr_error($json['Result']));
			}			
		}else{
			return template_error($result['msg']);
		}
	}
	/**
	 * 出场操作
	 *  http://smartgym.com/api/ZYRApi/ConfirmCheckOut/interface/
	 */
	function ConfirmCheckOut($interface){
		$shop_id=$interface['shop_id'];
		$card_no=$interface['card_no'];
		$member_id=$interface['member_id'];
		$this->before_method($shop_id);
		$result=http_get(self::ConfirmCheckOut,['CardNo'=>$card_no,'BranchID'=>$this->BranchID,"MemberID"=>$member_id,"CardNo"=>$card_no,"DoorID"=>$shop_id]);
		if($result['flag']){
			$json= $this->decrypt($result['data']);
			if($json['Result']==1){
				return template_success("成功(zyr)",$json);
			}else{
				return template_error($this->zyr_error($json['Result']));
			}			
		}else{
			return template_error($result['msg']);
		}
	}
	/**
	 * 智游人内门禁
	 * smartgym.com/api/ZRYApi/InnerDoor/interface/1/brakemachine_no/01
	 * */
	function InnerDoor($interface,$brakemachine_no){
		$shop_id=$interface['shop_id'];
		$card_no=$interface['card_no'];
		$device_code=$this->GetOrderDeviceCode($shop_id);
		if(intval($brakemachine_no)==intval($device_code)){//需要预约的内门禁
			$this->IsOrderOrClass($interface);
		}else{// 其他内门禁则需要权限
			return;
		}
	}
	
	/**
	 * 获取当前时间是预约还是打卡
	 * */	
	function IsOrderOrClass($interface){
		$shop_id=$interface['shop_id'];
		$card_no=$interface['card_no'];
		$list=cache("BikeOrder_".$shop_id);
		if(empty($list)){
			$list=db("Class")->where("shop_id=$shop_id")->select();
			if(empty($list)){
				db("OrderClassError")->insert(array("card_no"=>$card_no,"shop_id"=>$shop_id,"error_msg"=>"没有设置预约时间段"));
				return $this->ajax_error('','',"没有设置预约时间段");	
			}else{
				cache("BikeOrder_".$shop_id,$list);
			}
		  	
		}
		$time=date("H:i");
		foreach ($list as $key => $value) {
			if($time>=$value['order_start_time']&&$time<=$value['order_end_time']){//预约
			    $orderClass=db("OrderClass")->where("shop_id=".$value['shop_id']." and step=".$value['step']."  and card_no='$card_no'  and date_format(create_time,'%Y-%m-%d')=date_format(now(),'%Y-%m-%d')")->find();
			    if(!empty($orderClass)){
			    	db("OrderClassError")->insert(array("card_no"=>$card_no,"class_name"=>$value['class_name'],"shop_id"=>$shop_id,"error_msg"=>"您已经预约了"));
			    	return $this->ajax_error('','',"已经预约");	
			    }else{
			    	$has_order_count=db("OrderClass")->where("step=".$value['step']." and shop_id=".$value['shop_id']." and   date_format(create_time,'%Y-%m-%d')=date_format(now(),'%Y-%m-%d')")->count(1);
					if($has_order_count<$value['pcount']){
						db("OrderClass")->insert(array("card_no"=>$card_no,"step"=>$value['step'],"order_time"=>date("Y-m-d H:i:s"),"class_name"=>$value['class_name'],"shop_id"=>$shop_id));
						return $this->ajax_success("","","预约成功",FALSE,"0","1");	
					}else{
						db("OrderClassError")->insert(array("card_no"=>$card_no,"class_name"=>$value['class_name'],"shop_id"=>$shop_id,"error_msg"=>"预约人数已满"));
			    		return $this->ajax_error('','',"预约人数已满");
					}
			    }	
			}
			if($time>=$value['class_start_time']&&$time<=$value['class_end_time']){//上课
				$orderClass=db("OrderClass")->where("shop_id=".$value['shop_id']." and step=".$value['step']." and card_no='$card_no'  and date_format(create_time,'%Y-%m-%d')=date_format(now(),'%Y-%m-%d')")->find();
			    if(!empty($orderClass)){
			    	$orderClass['class_time']=date("Y-m-d H:i:s");
			    	db("OrderClass")->update($orderClass);
					return $this->ajax_success("","","上课成功",TRUE,"0");
			    		
			    }else{
			       	db("OrderClassError")->insert(array("card_no"=>$card_no,"class_name"=>$value['class_name'],"shop_id"=>$shop_id,"error_msg"=>"没有预约"));
			    	return $this->ajax_error('','',"没有预约");
			    }	
			}
		}
		db("OrderClassError")->insert(array("card_no"=>$card_no,"shop_id"=>$shop_id,"error_msg"=>"不在规定时间内打卡"));
		return $this->ajax_error('','',"不在规定时间内打卡");	
	}
	/**
	 * 获取预约设备的编号
	 * */
	function GetOrderDeviceCode($shop_id){
		$device_code=db("ClassDevice")->where("shop_id='$shop_id'")->fetchsql(true)->value("device_code");
		//预约设备编号
		$device_code=cache("BikeOrderDevice_".$shop_id);
		if(empty($device_code)){
			$device_code=db("ClassDevice")->where("shop_id='$shop_id'")->value("device_code");
			if(empty($device_code)){
				cache("BikeOrderDevice_".$shop_id,"-1");
				$device_code="-1";
			}else{
				cache("BikeOrderDevice_".$shop_id,$device_code);
			}
		}
		return $device_code;		
	}
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
